package com.xuliugen.javamybatis.demo.proxy.dynamicproxy;

import org.apache.ibatis.binding.BindingException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuliugen on 2017/11/9.
 */
public class MapperRegistry {

    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public <T> T getMapper(Class<T> type) {

        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance();
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            knownMappers.put(type, new MapperProxyFactory<T>(type));
        }
    }

}
